<template>
  <div class="author-detail">
    <!-- 检查 author 对象是否存在 -->
    <div class="author-info" v-if="author">
      <img :src="author.img " alt="Author Portrait" class="author-portrait"/>
      <div class="author-details">
        <!-- 确保 author.name 存在 -->
        <h1 class="author-name">{{ author.name }}</h1>
        <p class="author-birth">
          生于: {{ author.birth }}
          <span v-if="author.death">逝于: {{ author.death }}</span>
        </p>
        <p class="author-birthplace">出生地: {{ author.birthPlace }}</p>
        <p class="author-intro">简介: {{ author.intro }}</p>
      </div>
    </div>

    <div class="author-books">
      <!-- 如果 filteredBooks 存在且不为空，则显示书籍列表 -->
      <div v-if="filteredBooks && filteredBooks.length">
        <h2 class="goodbook">作品：</h2>
        <div class="book-g">
          <div v-for="book in filteredBooks" :key="book.id" class="book-card">
            <router-link
                :key="book.id"
                :to="{
                name: 'BookDetail',
                params: { bookType: book.bookType },
                query: { id: book.id }
              }"
                class="book-link"
            >
              <img :src="book.cover" alt="Book Cover" class="book-cover">
              <h3 class="book-title">{{ book.title }}</h3>
            </router-link>
          </div>
        </div>
      </div>
      <div v-else>
        <p>还未制作</p>
      </div>
    </div>
  </div>
</template>


<script>
import {authors} from '@/assets/data/authorsData'; // 导入所有作者数据
import {books} from '@/assets/data/booksData'; // 导入所有图书数据
import '@/assets/css/AuthorDetail.css'

export default {
  name: 'AuthorDetail',
  props: ['name'],
  data() {
    return {
      author: {},
      authors: authors, // 初始化 authors 数组
      books: books, // 初始化 books 数组
    };
  },
  created() {
    this.fetchAuthorDetails();
  },
  watch: {
    // 监听路由变化，重新获取作者详情
    '$route'(to, from) {
      this.fetchAuthorDetails();
    }
  },
  methods: {
    fetchAuthorDetails() {
      const authorName = this.$route.params.name;

      if (!authorName) {
        this.$router.replace({name: 'Home'});
        return;
      }

      this.author = this.authors.find(author => author.name === authorName);
    },
  },

  computed: {
    filteredBooks() {
      // 确保当 author 不存在时返回空数组
      return this.author ? books.filter(book => book.author.includes(this.author.name)) : [];
    },
  },
};
</script>
